<template>
  <div>
    <top-footer>
      <template #search>
        <px-form ref="queryRef" class="custom-form-ui" :model="queryParams" inline label-width="90px">
          <px-form-item label="科室">
            <px-select v-model="queryParams.className" filterable disabled @change="classNameChange">
              <px-option v-for="item in classNameList" :key="item.id" :label="item.itemName" :value="item.itemValue" />
            </px-select>
          </px-form-item>
          <px-form-item label="报表类型">
            <px-select v-model="queryParams.reportType" clearable filterable>
              <px-option v-for="(item, index) in reportTypeList" :key="index" :label="item" :value="item" />
            </px-select>
          </px-form-item>
          <px-form-item label="报表名称/类型">
            <px-input v-model="queryParams.commonValue" clearable />
          </px-form-item>
          <px-form-item class="option-item">
            <px-button type="primary" @click="searchAction">查询</px-button>
            <px-button @click="resetQuery">重置</px-button>
          </px-form-item>
        </px-form>
      </template>
      <template #btn>
        <div class="table-btn-group" style="overflow: hidden">
          <px-button v-has="'REPORT_LIST_GO_TEMPLATE'" type="primary" @click="gotoTemplate">报表模板</px-button>
          <px-button v-has="'REPORT_LIST_LOCAL_IMPORT'" type="primary" plain @click="importReportAction">导入报表</px-button>
          <px-button v-has="'REPORT_LIST_BATCH_DETLET'" @click="deleteRecordAction">批量删除</px-button>
          <px-radio-group v-model="queryParams.fixedReport" style="float: right" @change="searchAction()">
            <px-radio-button :label="true">日常报表</px-radio-button>
            <px-radio-button :label="false">本地报表</px-radio-button>
          </px-radio-group>
        </div>
      </template>
      <template #table="{ height }">
        <px-table
          v-loading="loading"
          :data="tableData"
          :height="height"
          border
          style="width: 100%"
          :show-overflow-tooltip="true"
          @selection-change="selectionChange"
        >
          <template #empty>
            <px-empty />
          </template>
          <px-table-column type="selection" fixed width="40" prop="selection" align="center" />
          <px-table-column label="序号" width="60" align="center" fixed="left">
            <template #default="{ $index }">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
            </template>
          </px-table-column>
          <px-table-column prop="reportName" label="报表名称" min-width="120">
            <template #default="scope">
              <px-link type="primary" @click="handleDetail(scope.row)">{{ scope.row.reportName }}</px-link>
            </template>
          </px-table-column>
          <px-table-column prop="reportCode" label="文档编码" min-width="120" />
          <px-table-column prop="reportType" label="报表类型" min-width="100">
            <template #default="scope">
              {{ scope.row.reportType?.reportList.join("、") }}
            </template>
          </px-table-column>
          <px-table-column prop="reportFormat" label="格式" min-width="80" />
          <px-table-column prop="reportMessage" label="描述" min-width="150" />
          <px-table-column prop="updateTime" label="修改日期" min-width="100" />
          <px-table-column prop="createUser" label="填写人" min-width="100" />

          <px-table-column label="操作" align="center" width="160">
            <template #default="scope">
              <px-tooltip effect="dark" content="详情" placement="top">
                <px-button v-has="'REPORT_LIST_ITEM_VIEW'" link type="primary" @click="handleDetail(scope.row)">
                  <px-icon><Document /></px-icon>
                </px-button>
              </px-tooltip>
              <px-tooltip effect="dark" content="编辑" placement="top">
                <px-button v-has="'REPORT_LIST_ITEM_EDIT'" link type="primary" @click="handleEdit(scope.row)">
                  <px-icon>
                    <EditPen />
                  </px-icon>
                </px-button>
              </px-tooltip>
              <px-tooltip effect="dark" content="删除" placement="top">
                <px-button v-has="'REPORT_LIST_ITEM_DELETE'" link type="primary" @click="handleDelete(scope.row)">
                  <px-icon>
                    <Delete color="red" />
                  </px-icon>
                </px-button>
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>
      </template>
      <template #foot>
        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          :total="total"
          @pagination="queryTable"
        />
      </template>
    </top-footer>
    <px-dialog v-model="editDialogVisible" title="编辑报表信息" width="500" @close="closeDialog">
      <px-form ref="formRef" :model="editFormParams" label-width="92px" label-position="right" :rules="editRules">
        <px-form-item label="报表名称" prop="reportName">
          <px-input v-model="editFormParams.reportName" />
        </px-form-item>
        <px-form-item label="文档编码" prop="reportCode">
          <px-input v-model="editFormParams.reportCode" />
        </px-form-item>
        <px-form-item label="报表类别" prop="reportType">
          <px-select v-model="editFormParams.reportType" multiple filterable allow-create default-first-option :reserve-keyword="false">
            <px-option v-for="(item, index) in reportTypeList" :key="index" :label="item" :value="item" />
          </px-select>
        </px-form-item>
        <px-form-item label="格式" prop="reportFormat">
          <px-input v-model="editFormParams.reportFormat" disabled />
        </px-form-item>
        <px-form-item label="描述" prop="reportMessage">
          <px-input v-model="editFormParams.reportMessage" type="textarea" />
        </px-form-item>
      </px-form>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="closeDialog">取消</px-button>
          <px-button type="primary" @click="editSubmit()"> 确定 </px-button>
        </span>
      </template>
    </px-dialog>
    <px-dialog v-model="uploadDialogVisible" title="导入报表" @close="closeDialog">
      <FileUpload
        ref="fileUploadRef"
        fileType="add"
        :fileLists="reportFileList"
        :reportTypeList="reportTypeList"
        @changeFileList="changeFileList"
        @saveFileStatus="saveFileStatus"
      />
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="closeDialog">取消</px-button>
          <px-button v-optimize:debounce="{ event: 'click', fn: () => uploadSubmit(), timeout: 500 }" type="primary" :disabled="fileStatusFlag">
            确定
          </px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  queryReportType,
  addReportRecord,
  deleteReportRecord,
  queryReportRecord,
  updateReportRecord,
  queryChildByTypeCodeAndItemValue
} from "@/api/report";
import { onMounted, onUnmounted, reactive, toRefs, ref, computed, nextTick } from "vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { useRouter } from "vue-router";
import TopFooter from "../components/TopFooter.vue";
import FileUpload from "../components/FileUpload.vue";
import { useRouterStoreHook } from "@/store/modules/router";
import { useNav } from "@/layout/hooks/useNav";
const { username } = useNav();

const routerStore = useRouterStoreHook();

defineOptions({
  name: "COMMON_REPORT_TEMPLATE"
});

const router = useRouter();

const classNameList = ref([]);
const reportTypeList = ref([]);
const tableData = ref([]);
const loading = ref(false);
const total = ref(0);
const editDialogVisible = ref(false);
const uploadDialogVisible = ref(false);
const formRef = ref();
const editFormParams = reactive({});
const editRules = reactive({
  reportName: [{ required: true, trigger: "blur", message: "请输入" }],
  reportCode: [{ required: true, trigger: "blur", message: "请输入" }],
  reportType: [{ required: true, trigger: "change", message: "请选择" }]
});

const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  className: routerStore.getSubject === "ALL" ? "" : routerStore.getSubject,
  reportType: "",
  commonValue: "",
  fixedReport: true
});
const getReportType = async () => {
  const res = await queryReportType({ className: queryParams.className }); //ELECTRICTITY
  reportTypeList.value = res;
};
const getClassNameList = async () => {
  const res = await queryChildByTypeCodeAndItemValue({ typeCode: "className" });
  classNameList.value = res;
};
const classNameChange = () => {
  getReportType();
};
// http://{host}:{port}/webroot/decision/sp/client/api/v3/entry?keyword=目录&entry=["一级目录","二级目录"]
const searchAction = () => {
  queryParams.pageNum = 1;
  queryTable();
};
const queryTable = async () => {
  try {
    loading.value = true;
    const res = await queryReportRecord(queryParams);
    tableData.value = res?.data || [];
    total.value = res?.total;
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
};
function resetQuery() {
  queryParams.pageNum = 1;
  queryParams.pageSize = 20;
  queryParams.className = routerStore.getSubject === "ALL" ? "" : routerStore.getSubject;
  queryParams.reportType = "";
  queryParams.commonValue = "";
  queryTable();
  getReportType();
}
const gotoTemplate = () => {
  router.push("/electricity/report/template");
};

const handleDetail = row => {
  if (row.singleCode) {
    const path = "/fullScreen/report/detail";
    const query = {
      template: row.reportModuleName + ".cpt",
      op: "write",
      singleCode: row.singleCode,
      id: row.id,
      date: row.createTime
    };
    const params = { path, query };
    const { href } = router.resolve(params);
    window.open(href, "_blank");
  } else {
    const path = "/fullScreen/file/preview";
    const query = { id: row.fileInfo.id, moduleName: row.fileInfo.moduleName, fileName: row.fileInfo.fileName, fileType: row.fileInfo.fileType };
    const params = { path, query };
    const { href } = router.resolve(params);
    window.open(href, "_blank");
  }
};
const handleEdit = row => {
  editDialogVisible.value = true;
  editFormParams.id = row.id;
  editFormParams.reportFormat = row.reportFormat;
  editFormParams.reportName = row.reportName;
  editFormParams.reportCode = row.reportCode;
  editFormParams.reportType = row.reportType?.reportList;
  editFormParams.reportMessage = row.reportMessage;
};
const handleDelete = row => {
  PxMessageBox.confirm(`是否删除该条记录数据？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await deleteReportRecord({ ids: [row.id] });
      PxMessage.success("删除成功");
      queryTable();
      getReportType();
    })
    .catch(() => {});
};

const closeDialog = () => {
  editDialogVisible.value = false;
  uploadDialogVisible.value = false;
};

const reportFileList = ref([]);
const fileStatusFlag = ref(false);
const changeFileList = val => {
  reportFileList.value = val;
  reportFileList.value.forEach(v => {
    v.reportName = v.originalName;
    // v.className = queryParams.className;
  });
};
// 文件是否上传完，是否可以保存
const saveFileStatus = val => {
  fileStatusFlag.value = val;
};
const importReportAction = () => {
  reportFileList.value = [];
  uploadDialogVisible.value = true;
};
const selectedRows = ref([]);
const selectionChange = val => {
  selectedRows.value = val;
};
const deleteRecordAction = () => {
  if (selectedRows.value.length == 0) {
    PxMessage.error("请先选择要删除的数据！");
    return;
  }
  let ids = selectedRows.value.map(v => v.id);
  PxMessageBox.confirm(`是否这些记录数据？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await deleteReportRecord({ ids });
      PxMessage.success("删除成功");
      queryTable();
      getReportType();
    })
    .catch(() => {});
};
const editSubmit = () => {
  formRef.value?.validate(async (valid, fields) => {
    if (valid) {
      let reportType = editFormParams.reportType ? { reportList: editFormParams.reportType } : null;
      let res = await updateReportRecord({ ...editFormParams, reportType });
      PxMessage.success("更新成功");
      closeDialog();
      queryTable();
      getReportType();
    } else {
      console.log("error submit!", fields);
    }
  });
};
const fileUploadRef = ref();
function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
}
const uploadSubmit = async () => {
  let params = [];
  reportFileList.value.forEach(v => {
    let {
      id,
      originalName,
      fileName,
      fileType,
      fileSize,
      fileUrl,
      moduleName,
      moduleId,
      accountId,
      accountName,
      status,
      createTime,
      updateTime,
      pic
    } = v;
    params.push({
      className: routerStore.getSubject === "ALL" ? "" : routerStore.getSubject,
      reportName: v.reportName,
      reportCode: v.reportCode,
      reportType: { reportList: v.reportType || [] },
      reportFormat: v.fileType,
      reportMessage: v.reportMessage,
      fileInfo: {
        id,
        originalName,
        fileName,
        fileType,
        fileSize,
        fileUrl,
        moduleName,
        moduleId,
        accountId,
        accountName,
        status,
        createTime,
        updateTime,
        pic
      },
      updateTime: formatDate(new Date()),
      createUser: username.value,
      updateUser: username.value
    });
  });
  if (params.length == 0) {
    PxMessage.error("请先上传文件");
    return;
  }
  fileUploadRef.value.tableFormRef?.validate(async validate => {
    if (validate) {
      await addReportRecord(params);
      PxMessage.success("上传成功");
      closeDialog();
      queryTable();
      getReportType();
    }
  });
};
onMounted(() => {
  getReportType();
  getClassNameList();
  queryTable();
  window.addEventListener("storage", e => {
    if (e.key != "listen_report_record_delete") return;
    queryTable();
    localStorage.removeItem("listen_report_record_delete");
  });
});
onUnmounted(() => {
  console.log("in unmount");
});
</script>
<style scoped lang="scss">
:deep(.px-select) {
  width: 100%;
}

:deep(.px-input) {
  width: 100%;
}

.table-btn-group {
  .px-button {
    margin-left: 8px;

    &:first-child {
      margin-left: 0;
    }
  }
}

.template-content {
  width: 100%;
}

.template-list {
  display: flex;
  flex-wrap: wrap;

  .temp-item {
    position: relative;
    width: 250px;
    height: 160px;
    margin-right: 24px;
    margin-bottom: 24px;
    cursor: pointer;
    background: blue;

    &.isLast {
      margin-right: 0;
    }

    .name {
      position: absolute;
      bottom: 40px;
      left: 5%;
      width: 90%;
      text-align: center;
    }
  }
}

:deep(.px-table-column--selection) {
  .cell {
    width: 40px;
  }
}

:deep(.px-table__header) {
  thead {
    tr {
      background-color: #e7eefb !important;

      th {
        font-size: 13px;
        font-weight: bold;
        color: #000;
        background-color: #e7eefb !important;
      }
    }
  }
}

:deep(.px-table--isfixedHeader .px-table__header-wrapper .px-table-fixed-column--right) {
  background-color: #e7eefb !important;
}

.px-icon {
  font-size: 16px !important;
}

:deep(.px-table__cell) {
  height: 42px;
  padding: 8px 0;
}

:deep(.cell) {
  line-height: 1.2;
}
</style>
